<template>
  <div :class="[$style.container]">
    <div :class="[$style.header]">
      <el-link :underline="false" @click="onBack"><i class="el-icon-back ft-lg"></i></el-link>
      <span class="ml-3">验证码</span>
    </div>
    <div :class="[$style.info]">
      <div :class="[$style.icon]"><span><svg-icon :icon="stepData.type"></svg-icon></span></div>
      <div :class="[$style.text]">{{stepData.identifier}}</div>
    </div>
    <el-form :model="form" :rules="rules" ref="fm">
      <el-form-item prop="code" required>
        <code-input v-model="form.code" :send-fn="sendFn"></code-input>
      </el-form-item>
    </el-form>

    <div :class="[$style.action]" class="mt-5">
      <el-button type="primary" :loading="submitting" @click="onNext" style="width: 100%;">下一步</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { checkCredentialCorrected, resetEmailCredential, resetPhoneCredential } from '@/api/account'
import { Component, Prop, Ref, Vue } from 'vue-property-decorator'

@Component
export default class Step2 extends Vue {
  @Ref() fm!: any

  @Prop() stepData!: any

  submitting = false

  form = {
    code: ''
  }

  get rules () {
    return {
      code: [
        { required: true, message: '请输入验证码' }
      ]
    }
  }

  sendFn () {
    if (this.stepData.type === 'phone') {
      return resetPhoneCredential(this.stepData.identifier)
    } else {
      return resetEmailCredential(this.stepData.identifier)
    }
  }

  onNext () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      this.submitting = true
      checkCredentialCorrected(this.stepData.identifier, this.stepData.type, this.form.code).then(data => {
        if (data) {
          this.stepData.code = this.form.code
          this.stepData.step = 3
        } else {
          this.$message.error('验证码错误')
        }
      }).finally(() => {
        this.submitting = false
      })
    })
  }

  onBack () {
    this.stepData.step = 1
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.header {
  margin-bottom: 12px;
  font-size: 16px;
}

.info {
  text-align: center;
}

.icon {
  font-size: 48px;
  color: $text-secondary-color;
}

.text {
  margin: 8px 0 24px;
  color: $text-secondary-color;
}

.action {
  display: flex;
  justify-content: space-between;
}
</style>
